package Sort2;

import java.util.Arrays;

public class Merge {
    public static void main(String[] args) {
        int[] arr={5,9,8,1,1,5,4};
//        merge(arr);
        headLoop(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void merge(int[] arr){
        _merge(arr,0,arr.length);
    }

    private static void _merge(int[] arr, int left, int right) {
        if(left>=right-1){
            return;
        }
        int mid=(left+right)/2;
        _merge(arr,left,mid);
        _merge(arr,mid,right);
        sort(arr,left,mid,right);
    }

    private static void sort(int[] arr, int left, int mid, int right) {
        int l=left;
        int r=mid;
        int size=right-left;
        int[] res=new int[size];
        int index=0;
        while(l<mid&&r<right){
            if(arr[l]<=arr[r]) {
                res[index++]=arr[l++];
            }else{
                res[index++]=arr[r++];
            }
        }
        while(l<mid){
            res[index++]=arr[l++];
        }
        while(r<right){
            res[index++]=arr[r++];
        }
        for(int i=0;i<size;i++){
            arr[i+left]=res[i];
        }
    }
    public static void headLoop(int[] arr){
        for(int i=1;i<arr.length;i*=2){
            for(int j=0;j<arr.length;j+=2*i){
                int left=j;
                int mid=j+i;
                if(j+i>=arr.length){
                    mid=arr.length;
                }
                int right=j+2*i;
                if(right>=arr.length){
                    right=arr.length;
                }
                sort(arr,left,mid,right);
            }
        }
    }

}
